package org.asiainfo.common.excel.core;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.asiainfo.common.core.utils.StreamUtils;
import org.asiainfo.common.core.utils.ValidatorUtils;
import org.asiainfo.common.json.utils.JsonUtils;

import java.util.Map;
import java.util.Set;

/**
 * 默认Excel监听器
 *
 * @author dotor-ww
 */
@Slf4j
@NoArgsConstructor
public class DefaultExcelListener<T> extends AnalysisEventListener<T> implements ExcelListener<T> {

    /**
     * 是否校验Validator,默认是
     */
    private Boolean isValidate = Boolean.TRUE;

    /**
     * excel表头数据
     */
    private Map<Integer, String> headMap;

    /**
     * 导入回执
     */
    private ExcelResult<T> excelResult;

    public DefaultExcelListener(Boolean isValidate) {
        this.excelResult = new DefaultExcelResult<>();
        this.isValidate = isValidate;
    }

    /**
     * 处理异常信息
     *
     * @param exception ExcelDataConvertException
     * @param context   Excel上下文
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        String errMsg = null;

        //判断是否是数据转换异常
        if (exception instanceof ExcelDataConvertException excelDataConvertException) {
            Integer rowIndex = excelDataConvertException.getRowIndex();
            Integer columnIndex = excelDataConvertException.getColumnIndex();
            errMsg = StrUtil.format("第{}行-第{}列-表头{}: 解析异常<br />", rowIndex + 1, columnIndex + 1, headMap.get(columnIndex));
            if (log.isDebugEnabled()) log.error(errMsg);
        }

        //判断是否是数据校验异常
        if (exception instanceof ConstraintViolationException constraintViolationException) {
            Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
            errMsg = StreamUtils.join(constraintViolations, ConstraintViolation::getMessage, ", ");
            if (log.isDebugEnabled()) log.error(errMsg);
        }

        excelResult.getErrorList().add(errMsg);
        throw new ExcelAnalysisException(errMsg);
    }

    /**
     * 收标头数据
     *
     * @param headMap 表头
     * @param context excel上下文
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        this.headMap = headMap;
        log.debug("解析到一条表头数据: {}", JsonUtils.toJsonString(headMap));
    }

    /**
     * 获取Excel解析结果
     *
     * @return Excel解析结果
     */
    @Override
    public ExcelResult<T> getExcelResult() {
        return excelResult;
    }

    /**
     * 每一行数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context analysis context
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
        if (isValidate) ValidatorUtils.validate(data);
        excelResult.getList().add(data);
    }

    /**
     * 解析完成
     *
     * @param context Excel上下文
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.debug("所有数据解析完成！");
    }
}
